﻿using NHibernate.Cfg;
using NHibernate.Tool.hbm2ddl;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using NHibernate;
using FluentNHibernate.Cfg;
using FluentNHibernate.Cfg.Db;

namespace SmallTune
{
    public class SessionFactory
    {
        private static string DbFile = @"D:\SmallTune.db";
        private static ISessionFactory _session;

        public static bool CreatedDB = false;

        public static ISessionFactory session
        {
            get
            {
                if (_session == null || _session.IsClosed)
                {
                    _session = CreateSessionFactory();
                }
                return _session;
            }
        }

        public static ISessionFactory CreateSessionFactory()
        {
            return Fluently.Configure()
              .Database(
                SQLiteConfiguration.Standard
                  .UsingFile(DbFile)
              )
              .Mappings(m =>
                m.FluentMappings.AddFromAssemblyOf<SessionFactory>())
              .ExposeConfiguration(BuildSchema)
              .BuildSessionFactory();
        }

        public static void BuildSchema(Configuration config)
        {

            if (!File.Exists(DbFile))
            {
                CreatedDB = true;
                // this NHibernate tool takes a configuration (with mapping info in)
                // and exports a database schema from it
                new SchemaExport(config)
                  .Create(false, true);
            }
        }
    }
}
